<template>
	<div>
		<a-modal
			:open="props.open"
			:width="
				props.modelInfo && props.modelInfo.width ?
					props.modelInfo.width
				:	'900px'
			"
			:title="
				props.modelInfo && props.modelInfo.title ?
					props.modelInfo.title
				:	'Basic Modal'
			"
			@ok="handleOk"
			okText="保存"
			:confirmLoading="modelConfig.confirmLoading"
			:destroyOnClose="modelConfig.destroyOnClose"
			@cancel="handleCancel"
		>
			<template #footer>
				<a-button key="back" @click="handleCancel">取消</a-button>
				<a-button
					key="submit"
					type="primary"
					:loading="loading"
					@click="handleOk"
					>保存</a-button
				>
			</template>
			<a-form
				ref="formRef"
				name="MatchmakerInfoForm"
				class="ant-advanced-search-form"
				:model="formState"
				@finish="onFinish"
				@finishFailed="onFinishFailed"
				:rules="rulesRef"
				:label-col="labelCol"
				:wrapper-col="wrapperCol"
			>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['name'].name"
							:label="labelMap['name'].label"
						>
							<a-input
								v-model:value="formState.name"
								:placeholder="'请填写' + labelMap['name'].label"
							></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['photoId'].name"
							:label="labelMap['photoId'].label"
						>
							<MyUpload
								v-model:value="formState.photoId"
								fromSystem="common"
								:fileInfo="photoFileInfo"
								@customImageRequest="
									async (file: any) => await customImageRequest(file, 'photo')
								"
								@handleRemove="handleRemove('photo')"
							>
							</MyUpload>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['birthDate'].name"
							:label="labelMap['birthDate'].label"
						>
							<a-date-picker
								v-model:value="formState.birthDate"
								:format="'YYYY-MM-DD'"
								:placeholder="'请选择' + labelMap['birthDate'].label"
								:getPopupContainer="
									(triggerNode: any) => {
										return triggerNode.parentNode;
									}
								"
								:show-time="false"
							/>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['contactPhone'].name"
							:label="labelMap['contactPhone'].label"
						>
							<a-input
								v-model:value="formState.contactPhone"
								:placeholder="'请填写' + labelMap['contactPhone'].label"
							></a-input>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['location'].name"
							:label="labelMap['location'].label"
						>
							<a-cascader
								v-model:value="formState.location"
								:options="locationTree"
								placeholder="请选择区域"
								:load-data="loadData"
								:fieldNames="{
									label: 'name',
									value: 'id',
									children: 'children',
								}"
								change-on-select
								@blur="handleLocationChange"
							/>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['entryDate'].name"
							:label="labelMap['entryDate'].label"
						>
							<a-date-picker
								v-model:value="formState.entryDate"
								:format="'YYYY-MM-DD'"
								:placeholder="'请选择' + labelMap['entryDate'].label"
								:getPopupContainer="
									(triggerNode: any) => {
										return triggerNode.parentNode;
									}
								"
								:show-time="false"
							/>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['expertise'].name"
							:label="labelMap['expertise'].label"
						>
							<a-input
								v-model:value="formState.expertise"
								:placeholder="'请填写' + labelMap['expertise'].label"
							></a-input>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['positionLevel'].name"
							:label="labelMap['positionLevel'].label"
						>
							<a-input
								v-model:value="formState.positionLevel"
								:placeholder="'请填写' + labelMap['positionLevel'].label"
							></a-input>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['userId'].name"
							:label="labelMap['userId'].label"
						>
							<a-select
								v-model:value="formState.userId"
								:placeholder="'请选择' + labelMap['userId'].label"
								:options="userList"
								:filter-option="filterOption"
								:field-names="{ value: 'id', label: 'code' }"
								show-search
								allow-clear
								:disabled="props?.modelInfo?.id != null"
							>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['wechatQrcodeId'].name"
							:label="labelMap['wechatQrcodeId'].label"
						>
							<MyUpload
								fromSystem="common"
								:fileInfo="qrcodeFileInfo"
								@customImageRequest="
									async (file: any) =>
										await customImageRequest(file, 'wechatQrcode')
								"
								@handleRemove="handleRemove('wechatQrcode')"
							></MyUpload>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row :gutter="24">
					<a-col :span="12">
						<a-form-item
							:name="labelMap['status'].name"
							:label="labelMap['status'].label"
						>
							<a-select
								v-model:value="formState.status"
								:placeholder="'请选择' + labelMap['status'].label"
								:options="statusList"
								show-search
								allow-clear
								:disabled="true"
							>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item
							:name="labelMap['gender'].name"
							:label="labelMap['gender'].label"
						>
							<a-select
								v-model:value="formState.gender"
								:placeholder="'请选择' + labelMap['gender'].label"
								:options="genderList"
								show-search
								allow-clear
							>
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>
	</div>
</template>
<script lang="ts" setup>
import {
	MatchmakerInfoDetail,
	rulesRef,
	labelMap,
	statusList,
	genderList,
} from './matchmakerInfoDetailTs';
import {
	getMatchmakerInfoDetail,
	addOrEditMatchmakerInfo,
} from '@/api/matchmakerInfo/matchmakerInfo/matchmakerInfoTs';
import { getUserInfoList } from '@/api/userInfo/userInfo/userInfoTs';
import { reduceMoneyInfo } from '@/api/userBalanceInfo/index';
import { message, FormInstance } from 'ant-design-vue';
import { ModelInfo } from '../matchmakerInfoListTs';
import { getLocationTree } from '@/api/eventInfo/eventInfo/eventInfoTs';
import { getDefaultAmountConfigQueryCode } from '@/api/commonInfo/defaultAmountConfig/defaultAmountConfigTs';
import dayjs from 'dayjs';
import { filterOption } from '@/utils/common';

const labelCol = ref({ span: 5 });
const wrapperCol = ref({ span: 19 });

let loading = ref<boolean>(false);

const formRef = ref<FormInstance>();

const firstChange = ref<boolean>(true);

const locationTree = ref<any[]>([]);

let photoFileInfo = ref<any>(null);

let qrcodeFileInfo = ref<any>(null);

const userList = ref<any>([]);

const amountConfig = ref<any>(null);

const customImageRequest = async (file: any, type: string) => {
	if (type === 'photo') {
		formState.value.photoId = file.id;
	} else if (type === 'wechatQrcode') {
		formState.value.wechatQrcodeId = file.id;
	}
	return true;
};

const handleRemove = (type: string) => {
	if (type === 'photo') {
		formState.value.photoId = null;
	} else if (type === 'wechatQrcode') {
		formState.value.wechatQrcodeId = null;
	}
};

const handleLocationChange = (value: any) => {
	if (formState.value?.location?.length == 3) {
		firstChange.value = false;
		return;
	}
	firstChange.value = false;
	formState.value.location = [];
};

const getLocationTreeInfo = async (parentId: number): Promise<any> => {
	const {
		data,
		code,
		message: messageInfo,
	} = await getLocationTree({ parentId }).catch((error: any) => {
		message.error(error?.message || '查询失败！');
	});
	if (code == '200') {
		return data;
	} else {
		message.error(messageInfo || '查询失败！');
		return null;
	}
};

const loadData = async (selectedOptions: any[]) => {
	const targetOption = selectedOptions[selectedOptions.length - 1];
	console.log('loadData', selectedOptions, targetOption);
	targetOption.loading = true;
	targetOption.children = await getLocationTreeInfo(targetOption.id);
	if (targetOption.children.length == 0) {
		return;
	}
	targetOption.children.forEach((item: any) => {
		if (targetOption.level == 1) {
			item.isLeaf = false;
			item.level = 2;
		} else {
			item.isLeaf = true;
			item.level = 3;
		}
	});
};

const modelConfig = {
	confirmLoading: true,
	destroyOnClose: true,
};

interface Props {
	open?: boolean;
	modelInfo?: ModelInfo;
}
const props = defineProps<Props>();

let formState = ref<MatchmakerInfoDetail>({});

const emit = defineEmits(['handleOk', 'handleCancel']);

const handleOk = (): void => {
	loading.value = true;
	if (formRef.value) {
		formRef.value
			.validateFields()
			.then(() => saveMatchmakerInfoManager())
			.catch(() => {
				loading.value = false;
			});
	}
};

const handleCancel = (): void => {
	emit('handleCancel', false);
};

//保存红娘信息表信息
const saveMatchmakerInfoManager = async (): Promise<void> => {
	let method = '';
	let params = {
		id: formState.value.id,
		photoId: formState.value.photoId,
		name: formState.value.name,
		birthDate: formState.value.birthDate,
		contactPhone: formState.value.contactPhone,
		provinceId:
			firstChange.value ?
				formState.value.provinceId
			:	(formState.value?.location?.length ?
					formState.value?.location[0]
				:	null) || null,
		cityId:
			firstChange.value ?
				formState.value.cityId
			:	(formState.value?.location?.length ?
					formState.value?.location[1]
				:	null) || null,
		districtId:
			firstChange.value ?
				formState.value.districtId
			:	(formState.value?.location?.length ?
					formState.value?.location[2]
				:	null) || null,
		entryDate: formState.value.entryDate,
		expertise: formState.value.expertise,
		positionLevel: formState.value.positionLevel,
		wechatQrcodeId: formState.value.wechatQrcodeId,
		userId: formState.value.userId,
		status: formState.value.status,
		gender: formState.value.gender,
	};
	// 如果是新增，则有消费现金接口，否则直接走修改接口
	if (formState.value.id) {
		method = 'put';
		addOrEditMatchmakerInfo(method, params)
			.then((res) => {
				if (res.code == '200') {
					message.success((res && res.message) || '保存成功！');
					formState.value = {};
					emit('handleOk', false);
				} else {
					message.error((res && res.message) || '保存失败！');
				}
			})
			.catch((error: any) => {
				message.error(error?.message || '查询失败！');
			})
			.finally(() => {
				loading.value = false;
			});
	} else {
		method = 'post';
		let currentParams = {
			relatedBusinessInfo: JSON.stringify(params),
			type: 'matchmaker_save',
			amount: amountConfig.value.amount,
			userId: formState.value.userId,
			source: 'end',
		};
		const { code, message: messageInfo } = await reduceMoneyInfo(currentParams)
			.catch((error: any) => {
				message.error(error?.message || '查询失败！');
			})
			.finally(() => {
				loading.value = false;
			});
		if (code == '200') {
			message.success('创建订单成功，请到订单中进行审核！');
			formState.value = {};
			emit('handleOk', false);
		} else {
			message.error(messageInfo || '保存失败！');
		}
	}
};

const onFinish = (values: any): void => {
	console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any): void => {
	console.log('Failed:', errorInfo);
};

// 查询用户信息
const getUserInfoListInfo = async () => {
	let params = {};
	let res = await getUserInfoList(params);
	const { code, data, message: messageInfo } = res;
	if (code === '200') {
		userList.value = data;
	} else {
		userList.value = [];
		message.warn(messageInfo || '失败，请联系管理员！');
	}
};

const getDefaultAmountConfigQueryCodeInfo = async () => {
	const {
		code,
		data,
		message: messageInfo,
	} = await getDefaultAmountConfigQueryCode({
		code: 'matchmaker_save',
	});
	if (code == '200') {
		amountConfig.value = data;
	} else {
		console.error(messageInfo || '查询失败！');
	}
};

const init = async (): Promise<void> => {
	if (props.modelInfo) {
		if (props.modelInfo.id) {
			getMatchmakerInfoDetail(props.modelInfo.id)
				.then((res) => {
					if (res.code == '200') {
						formState.value = res.data;
						modelConfig.confirmLoading = false;
						firstChange.value = true;
						formState.value.birthDate =
							res.data?.birthDate ? dayjs(res.data?.birthDate) : null;
						formState.value.entryDate =
							res.data?.entryDate ? dayjs(res.data?.entryDate) : null;
						formState.value.location = [
							res.data?.provinceName,
							res.data?.cityName,
							res.data?.districtName,
						];
						photoFileInfo.value = {
							id: res.data?.photoId,
							url: res.data?.photoFileInfoVo?.preUrl || '',
						};
						qrcodeFileInfo.value = {
							id: res.data?.wechatQrcodeUrl,
							url: res.data?.wechatQrcodeFileInfoVo?.preUrl || '',
						};
					} else {
						message.error((res && res.message) || '查询失败！');
					}
				})
				.catch((error: any) => {
					message.error(error?.message || '查询失败！');
				});
		} else {
			photoFileInfo.value = {};
			qrcodeFileInfo.value = {};
			modelConfig.confirmLoading = false;
			formState.value = {
				status: 1,
			};
			await getDefaultAmountConfigQueryCodeInfo();
		}
	}
};

watch(
	() => props.open,
	async (newVal) => {
		if (newVal) {
			init();
			locationTree.value = await getLocationTreeInfo(0);
			await getUserInfoListInfo();
			locationTree.value.forEach((item) => {
				item.isLeaf = false;
				item.level = 1;
			});
		}
	},
	{
		immediate: true,
		deep: true,
	},
);

defineExpose({ handleOk, handleCancel });
</script>
<style lang="scss" scoped></style>
